package com.lv.fast.aop;

import com.lv.fast.DO.SysLogDO;
import com.lv.fast.annotation.SysLog;
import com.lv.fast.constant.HttpConstant;
import com.lv.fast.constant.JsonConstant;
import com.lv.fast.dao.SysLogDao;
import com.lv.fast.enums.StatusEnum;
import com.lv.fast.util.HttpRequestUtil;
import com.lv.fast.util.SysUserUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 记录系统日志aop
 * @author lv
 * @version 1.0.0
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class SysLogAop {

    private final HttpServletRequest request;

    private final SysLogDao sysLogDao;

    @Pointcut("@annotation(log)")
    public void pointcut(SysLog log) {}

    @Around("pointcut(sysLog)")
    public Object around(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        String status = StatusEnum.SUCCESS.getCode();
        try{
            Object proceed = joinPoint.proceed();
            return proceed;
        }catch (Exception e){
            status = StatusEnum.FAIL.getCode();
            throw e;
        }finally {
            //记录日志
            saveLog(joinPoint,sysLog,status);
        }
    }

    @SneakyThrows
    public void saveLog(ProceedingJoinPoint joinPoint, SysLog log, String status){
        SysLogDO sysLogDO = new SysLogDO();
        sysLogDO.setUserId(SysUserUtil.getCurrentLoginUserId());
        sysLogDO.setUserName(SysUserUtil.getCurrentLoginUser().getName());
        sysLogDO.setOperateType(log.operateType().getCode());
        sysLogDO.setOperation(log.value());
        String requestIp = HttpRequestUtil.getRequestIp(request);
        if (requestIp.length() > HttpConstant.MAX_IP_LENGTH){
            requestIp = requestIp.substring(0, HttpConstant.MAX_IP_LENGTH);
        }
        sysLogDO.setIp(requestIp);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        sysLogDO.setMethod(className+JsonConstant.SEPARATOR_BEAN_NAME+methodName);
        sysLogDO.setParams(JsonConstant.objectMapper.writeValueAsString(args));
        sysLogDO.setOperationStatus(status);
        sysLogDao.insert(sysLogDO);
    }
}
